package com.mulong.mall.service.impl;

import java.util.*;
import java.util.stream.Collectors;

import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.mulong.mall.constants.Constants;
import com.mulong.mall.domain.bo.distributor.*;
import com.mulong.mall.domain.param.distributor.*;
import com.mulong.mall.domain.result.distributor.*;
import com.mulong.mall.service.DistributorFinanceService;
import com.mulong.mall.service.support.DistributorFinanceSupport;
import com.mulong.mall.util.MallRequestContext;

import cn.hutool.core.date.DateUtil;
import lombok.extern.slf4j.Slf4j;

import com.mulong.common.dao.mall.FinanceDao;
import com.mulong.common.domain.pojo.mall.AccountRecharge;
import com.mulong.common.domain.pojo.mall.AccountTransaction;
import com.mulong.common.domain.pojo.mall.custom.AccountRechargeQuery;
import com.mulong.common.domain.pojo.mall.custom.AccountTransactionQuery;
import com.mulong.common.exception.ErrorEnums;
import com.mulong.common.exception.MulongException;
import com.mulong.common.util.MulongUtil;

/**
 * FinanceServiceImpl
 * 
 * @author mulong
 * @data 2021-05-29 21:36:08
 */
@Slf4j
@Service
public class DistributorFinanceServiceImpl implements DistributorFinanceService {
    @Autowired
    private FinanceDao financeDao;
    @Autowired
    private DistributorFinanceSupport distributorFinanceSupport;

    /**
     * @author mulong 
     */
    @Override
    public GetFinanceAccountRechargeByPageResult getAccountRechargeByPage(GetFinanceAccountRechargeByPageParam param) {
        AccountRechargeQuery query = new AccountRechargeQuery();
        query.setGatewayAccountId(MallRequestContext.getGatewayAccountId());
        query.setTransactionSerialNo(param.getTransactionSerialNo());
        query.setStatus(param.getStatus());
        query.setOrderBy("`create_time` DESC");
        int pageNo = param.getPageNo() == null ? Constants.DEFAULT_PAGE_NO : param.getPageNo();
        int pageSize = param.getPageSize() == null ? Constants.DEFAULT_PAGE_SIZE : param.getPageSize();
        PageHelper.startPage(pageNo, pageSize, true);
        Page<AccountRecharge> page = (Page<AccountRecharge>) financeDao.queryAccountRecharge(query);
        GetFinanceAccountRechargeByPageResult getFinanceAccountRechargeByPageResult = new GetFinanceAccountRechargeByPageResult(page.getPageNum(), page.getPageSize(), (int)page.getTotal());
        List<AccountRecharge> list = page.getResult();
        if (!CollectionUtils.isEmpty(list)) {
            getFinanceAccountRechargeByPageResult.setResult(list.stream().map(FinanceAccountRecharge::new).collect(Collectors.toList()));
        }
        return getFinanceAccountRechargeByPageResult;
    }

    /**
     * @author mulong 
     */
    @Override
    public ResponseEntity<byte[]> downloadAccountRecharge() {
        String fileName = "充值.xls";
        // get data
        AccountRechargeQuery query = new AccountRechargeQuery();
        query.setGatewayAccountId(MallRequestContext.getGatewayAccountId());;
        query.setOrderBy("`create_time` ASC");
        List<AccountRecharge> records = financeDao.queryAccountRecharge(query);
        // build content
        byte[] content = null;
        try (HSSFWorkbook workbook = new HSSFWorkbook()) {
            HSSFSheet sheet = workbook.createSheet(Constants.DISTRIBUTOR_DOWNLOAD_RECHARGE_SHEET_NAME);            
            List<String> titles = Constants.DISTRIBUTOR_DOWNLOAD_RECHARGE_SHEET_TITLE;
            MulongUtil.addTitle(workbook, sheet, titles);
            HSSFCellStyle defaultStyle = MulongUtil.getDefaultCellStyle(workbook);
            int lastRowNum = sheet.getLastRowNum();
            for (int j = 0; j < records.size(); j++) {
                AccountRecharge record = records.get(j);
                HSSFRow row = sheet.createRow(j + (lastRowNum + 1));
                distributorFinanceSupport.addRow(row, record, defaultStyle);
            }
            content = MulongUtil.toByteArray(workbook); 
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            content = null;
        }
        if (content == null) {
            throw new MulongException(ErrorEnums.HANDLE_FAILED_TEMPLETE.format("导出数据异常"));
        }
        // build response
        return MulongUtil.buildDownloadResponse("application/octet-stream", fileName, content);
    }

    /**
     * @author mulong 
     */
    @Override
    public GetFinanceAccountTransactionByPageResult getAccountTransactionByPage(GetFinanceAccountTransactionByPageParam param) {
        AccountTransactionQuery query = new AccountTransactionQuery();
        query.setGatewayAccountId(MallRequestContext.getGatewayAccountId());
        query.setTransactionNo(param.getTransactionNo());
        query.setTransactionCategory(param.getTransactionCategory());
        if (param.getTransactionDateFrom() != null) {
            query.setTransactionTimeFrom(param.getTransactionDateFrom());
        }
        if (param.getTransactionDateTo() != null) {
            query.setTransactionTimeTo(DateUtil.offsetDay(param.getTransactionDateTo(), 1));
        }
        query.setOrderBy("`create_time` DESC");
        int pageNo = param.getPageNo() == null ? Constants.DEFAULT_PAGE_NO : param.getPageNo();
        int pageSize = param.getPageSize() == null ? Constants.DEFAULT_PAGE_SIZE : param.getPageSize();
        PageHelper.startPage(pageNo, pageSize, true);
        Page<AccountTransaction> page = (Page<AccountTransaction>) financeDao.queryAccountTransaction(query);
        GetFinanceAccountTransactionByPageResult getFinanceAccountTransactionByPageResult = new GetFinanceAccountTransactionByPageResult(page.getPageNum(), page.getPageSize(), (int)page.getTotal());
        List<AccountTransaction> list = page.getResult();
        if (!CollectionUtils.isEmpty(list)) {
            getFinanceAccountTransactionByPageResult.setResult(list.stream().map(FinanceAccountTransaction::new).collect(Collectors.toList()));
        }
        return getFinanceAccountTransactionByPageResult;
    }

    /**
     * @author mulong 
     */
    @Override
    public ResponseEntity<byte[]> downloadAccountTransaction() {
        String fileName = "交易流水.xls";
        // get data
        AccountTransactionQuery query = new AccountTransactionQuery();
        query.setGatewayAccountId(MallRequestContext.getGatewayAccountId());;
        query.setOrderBy("`transaction_no` ASC");
        List<AccountTransaction> records = financeDao.queryAccountTransaction(query);
        // build content
        byte[] content = null;
        try (HSSFWorkbook workbook = new HSSFWorkbook()) {
            HSSFSheet sheet = workbook.createSheet(Constants.DISTRIBUTOR_DOWNLOAD_TRANSACTION_SHEET_NAME);            
            List<String> titles = Constants.DISTRIBUTOR_DOWNLOAD_TRANSACTION_SHEET_TITLE;
            MulongUtil.addTitle(workbook, sheet, titles);
            HSSFCellStyle defaultStyle = MulongUtil.getDefaultCellStyle(workbook);
            int lastRowNum = sheet.getLastRowNum();
            for (int j = 0; j < records.size(); j++) {
                AccountTransaction record = records.get(j);
                HSSFRow row = sheet.createRow(j + (lastRowNum + 1));
                distributorFinanceSupport.addRow(row, record, defaultStyle);
            }
            content = MulongUtil.toByteArray(workbook); 
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            content = null;
        }
        if (content == null) {
            throw new MulongException(ErrorEnums.HANDLE_FAILED_TEMPLETE.format("导出数据异常"));
        }
        // build response
        return MulongUtil.buildDownloadResponse("application/octet-stream", fileName, content);
    }

}
